package controller;

import java.net.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class MusicTransferClient {

	private final String serverIP = "10.30.92.4";
	private final int serverPort = 9999;
	private Socket _mSocket;

	DataInputStream in = null;
	DataOutputStream out = null;

	private String command = "";
	private String musicInfo = "";
	private String listInfo = "";
	private String userName = "";
	private String lists = "";
	private String userLikeListID = "";

	private int taskProgress = 0;

	MusicTransferClient(String command) {
		this._mSocket = null;
		this.command = command;
		Thread startThread = new Thread(new Runnable() {
			public void run() {
				startClient();
			}
		});
		startThread.start();
	}

	public String[] getMusicInfo() {
		String[] info = musicInfo.split("\t");
		return info;
	}

	public String getListInfo() {
		return listInfo;
	}

	public int getProgress() {
		return taskProgress;
	}

	public String getUserName() {
		return userName;
	}

	public String getLists() {
		return lists;
	}

	public String getULLID() {
		return userLikeListID;
	}

	private void receiveFile(int mltag) {
		try {
			String fileName = in.readUTF();
			System.out.println("Received File Name = " + fileName);
			int fileLength = (int) in.readLong();
			System.out.println(fileLength);
			// 保存路径
			File file;
			if (mltag == 0)//歌曲
				file = new File(".\\src\\main\\resources\\temp\\" + File.separator + "m" + command.split("\t")[1] + ".tmp");
			else if (mltag == 1)//歌词
				file = new File(".\\src\\main\\resources\\temp\\" + File.separator + "l" + command.split("\t")[1] + ".tmp");
			else if (mltag == 2)//封面
				file = new File(".\\src\\main\\resources\\temp\\" + File.separator + "c" + command.split("\t")[1] + ".tmp");
			else file = null;
			BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
			System.out.println("Received File size = " + fileLength / 1024 + "KB");

			// 开始接收
			byte[] content = new byte[2048];
			int offset = 0;
			int numReadBytes = 0;
			while (offset < fileLength && (numReadBytes = in.read(content)) > 0) {
				output.write(content, 0, numReadBytes);
				offset += numReadBytes;
			}
			System.out.println("numReadBytes = " + numReadBytes);
			if (offset < fileLength) {
				numReadBytes = in.read(content);
				System.out.println("File content error at server side");
			} else {
				System.out.println("File Receive Task has done correctly");
			}
			BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(_mSocket.getOutputStream()));
			bufferedWriter.write("DONE\r\n");
			bufferedWriter.flush();

			output.close();
		} catch (IOException ignored) {
		}

	}

	private void receiveMusic() {
		try {
			out.write(command.getBytes());
			out.flush();
			// 接收歌曲
			receiveFile(0);
			// 接收歌词
			receiveFile(1);
			// 接收歌曲信息
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1)
				musicInfo += (new String(buf, 0, len, "UTF-8"));

			System.out.println(musicInfo);
			if (!musicInfo.equals("\t"))
				taskProgress = 1;
			else
				taskProgress = -1;

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void receiveList() {
		try {
			out.write(command.getBytes());
			out.flush();

			receiveFile(2);

			// 接收歌单信息
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1)
				listInfo += (new String(buf, 0, len, "UTF-8"));
			if (!listInfo.equals("\t")) taskProgress = 1;
			else taskProgress = -1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void setFavoriteMusic() {
		try {
			out.write(command.getBytes());
			out.flush();
			// 接收成功消息
			BufferedInputStream streamReader = new BufferedInputStream(in);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(streamReader));
			String doneMsg = bufferedReader.readLine();
			if ("Success".equals(doneMsg)) {
				taskProgress = 1;
			} else taskProgress = -1;

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void signIn() {
		try {
			out.write(command.getBytes());
			out.flush();
			// 接收用户名
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1)
				userName += (new String(buf, 0, len, "UTF-8"));
			if (!userName.equals("\t")) taskProgress = 1;
			else taskProgress = -1;
			System.out.println(userName);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void signUp() {
		try {
			out.write(command.getBytes());
			out.flush();
			BufferedInputStream streamReader = new BufferedInputStream(in);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(streamReader));
			String doneMsg = bufferedReader.readLine();
			if ("Success".equals(doneMsg)) {
				taskProgress = 1;
			} else taskProgress = -1;

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void receiveListInfo() {
		try {
			out.write(command.getBytes());
			out.flush();

			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1)
				lists += (new String(buf, 0, len, "UTF-8"));
			if (!lists.equals("\t")) taskProgress = 1;
			else taskProgress = -1;
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void getUserLikeList() {
		try {
			out.write(command.getBytes());
			out.flush();
			// 接收歌单ID
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1)
				userLikeListID += (new String(buf, 0, len, "UTF-8"));
			if (!userLikeListID.equals("\t")) taskProgress = 1;
			else taskProgress = -1;
			System.out.println("user likes list " + userLikeListID);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void setFavoriteList() {
		try {
			out.write(command.getBytes());
			out.flush();
			// 接收成功消息
			BufferedInputStream streamReader = new BufferedInputStream(in);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(streamReader));
			String doneMsg = bufferedReader.readLine();
			if ("Success".equals(doneMsg)) {
				taskProgress = 1;
			} else taskProgress = -1;


		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void startClient() {
		try {
			if (serverIP != null && serverPort != 0) {
				_mSocket = new Socket(serverIP, serverPort);
				if (_mSocket.getRemoteSocketAddress() != null)
					System.out.println("client connected to " + _mSocket.getRemoteSocketAddress());
				in = new DataInputStream(_mSocket.getInputStream());
				out = new DataOutputStream(_mSocket.getOutputStream());

				String[] cmds = command.split("\t");
				switch (cmds[0]) {
					case "M":
						receiveMusic();
						break;
					case "L":
						receiveList();
						break;
					case "F":
						setFavoriteMusic();
						break;
					case "I":
						signIn();
						break;
					case "U":
						signUp();
						break;
					case "UF":
						receiveListInfo();
						break;
					case "FL":
						setFavoriteList();
						break;
					case "UL":
						getUserLikeList();
						break;
				}
				_mSocket.close();

			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}